
import router from '@/router'
let registerRouteFresh = true // 定义标识，记录路由是否添加
const pages = import.meta.glob('../views/**/index.vue')
const lauoytCom = import.meta.glob('../layout/index.vue')
const lauoyVla = lauoytCom['../layout/index.vue']

router.beforeEach(async (to, from, next) => {
  let res = [
    {
      path: '/test',
      name: '测试1',
      meta: { title: '测试1' },
      component: '',
      children: [
        {
          path: '/test1',  //这里加 /  就在地址栏直接显示 /mgmtUser
          name: '测试111',
          meta: { title: '用户管理123' },
          component: '../views/modules/test1/index.vue',
        },
        {
          path: '/test12',  //这里加 /  就在地址栏直接显示 /mgmtUser
          name: '测试22222222',
          meta: { title: '用2222222' },
          component: '../views/modules/test2/index.vue',
        }
      ]
    },
    {
      path: '/test4',
      name: '测试4A',
      meta: { title: '测试4B' },
      component: '',
      children: [
        {
          path: '/test14',
          name: '测试4C',
          meta: { title: '用户管理44D' },
          component: '../views/modules/test1/index.vue',
        },
      ]
    }
  ]
  let arr = []
  res.forEach((value) => {
    let child = []  // 子路由数据格式处理
    if (value.children && value.children.length === 1) {
      value.children.filter((val) => {
        child.push({
          name: val.name,
          path: val.path,
          meta: val.meta,
          component: pages[val.component]
        })
      })
    }
    if (value.children && value.children.length > 1) {
      value.children.filter((val) => {
        child.push({
          name: val.name,
          path: val.path,
          meta: val.meta,
          component: pages[val.component]
        })
      })
    }
    arr.push({
      name: value.name,
      path: value.path,
      meta: value.meta,
      component: lauoyVla,
      children: child
    })
  })
  if (registerRouteFresh) {
    arr.forEach((val) => {
      router.addRoute(val)
      router.options.routes.push(val)
    })
    console.log(router.options.routes, 3)
    next({ ...to, replace: true })
    registerRouteFresh = false
  } else {
    console.log(router.options.routes, 2)
    next()
  }
})
